const express = require('express')
const path = require('path')
const fs = require('fs')
const multer = require('multer')
const router = express.Router()

router.post(
  '/img',
  multer({
    //设置文件存储路径
    dest: 'uploads/images', //upload文件如果不存在则会自己创建一个。
  }).single('file'),
  (req, res) => {
    let oldname = req.file.path
    let newname = req.file.path + path.parse(req.file.originalname).ext //.jpg
    fs.renameSync(oldname, newname) //将老的文件名改成新的有后缀的文件 #同步写法
    res.send({
      code: 0,
      url:
        'http://localhost:3000/upload/' +
        req.file.filename +
        path.parse(req.file.originalname).ext, // 返回给浏览器一个磁盘地址和请求路径
    })
  }
)

router.post('/del', (req, res) => {
  const { url } = req.body
  const arr = url.split('/')
  const delName = arr[arr.length - 1]
  fs.unlink(`./uploads/images/${delName}`, (err) => {
    if (err) {
      res.send({
        code: 500,
        message: '文件删除失败',
      })
      return
    }
    res.send({
      code: 0,
      message: '文件删除成功',
    })
  })
})

module.exports = router
